package net.mobgame.common;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;

public class GPSService extends Service {
	public final static String INTENT_FILTER_ACTION = "net.mobgame.GPS_RECEIVER";
	private LocationManager mLocationManager;
	private GPSListener listener;
	private Thread mThread;
	private long TIME = 10000;
	private int DISTANCE = 5;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mThread = new Thread(new Runnable() {
			@Override
			public void run() {
				
				mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
				Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				
				if(locationNet==null && locationGPS==null){
//					Log.e("net.mobgame.GPSService", "net.mobgame.common.GPSService: no GPS");
				}else{
					Looper.prepare();
					listener = new GPSListener();
					long GPSLocationTime = 0;
					if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }

					long NetLocationTime = 0;

					if (null != locationNet) {
						NetLocationTime = locationNet.getTime();
					}

					if ( 0 < GPSLocationTime - NetLocationTime ) {
						mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME, DISTANCE, listener);
						 
					} else{
						mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, listener);
					}
					Looper.loop();
				}
			 
				
			}
		});
		mThread.start();
	}

	private class GPSListener implements LocationListener {

		@Override
		public void onLocationChanged(Location arg0) {
			
			double latitude = arg0.getLatitude();
			double longitude = arg0.getLongitude();
			
			if(latitude>0 || longitude>0){
			Intent i = new Intent(INTENT_FILTER_ACTION);
			i.putExtra("lat", latitude);
			i.putExtra("lon", longitude);
			sendBroadcast(i);
			}
		}

		@Override
		public void onProviderDisabled(String arg0) {
		}

		@Override
		public void onProviderEnabled(String arg0) {
		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		}
	}
}